package com.cherish.screen.controller;


import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.cherish.screen.db.entity.ExceptionLog;
import com.cherish.screen.service.ExceptionLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/screen")
public class IndexController {

    @Autowired
    private ExceptionLogService logService;

    @GetMapping("/")
    public String index() throws Exception {
        return "index";
    }

    @GetMapping("/index")
    public String index1() throws Exception {
        return "index";
    }

    @GetMapping("/login")
    public String login() throws Exception {
        return "login";
    }

    @GetMapping("/4yue")
    public String yue() throws Exception {
        return "4yue";
    }

    @GetMapping("/test")
    public String test() throws Exception {
        return "test";
    }

    @GetMapping("/kuayu")
    public String kuayu() throws Exception {
        return "kuayu";
    }

    @ResponseBody
    @PostMapping(value = "restore", produces = "application/json;charset=UTF-8")
    public String restore(@RequestBody ExceptionLog exceptionLog, HttpServletResponse response) throws Exception {
        System.out.println(exceptionLog.toString());

        logService.insert(exceptionLog);

        return getSuccessData().toJSONString();
    }

    @GetMapping("admin")
    public String admin(Model model) throws Exception {

        List<ExceptionLog> logs = logService.selectAll();

        model.addAttribute("logs", logs);
        return "admin";
    }

    private JSONObject getSuccessData() {
        JSONObject json = new JSONObject();
        json.put("status", 200);
        json.put("message", "test seccess");
        return json;
    }

    //Unicode转中文方法
    private static String unicodeToCn(String unicode) {
        /** 以 \ u 分割，因为java注释也能识别unicode，因此中间加了一个空格*/
        String[] strs = unicode.split("\\\\u");
        String returnStr = "";
        // 由于unicode字符串以 \ u 开头，因此分割出的第一个字符是""。
        for (int i = 1; i < strs.length; i++) {
            returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
        }
        return returnStr;
    }

    //中文转Unicode
    private static String cnToUnicode(String cn) {
        char[] chars = cn.toCharArray();
        String returnStr = "";
        for (int i = 0; i < chars.length; i++) {
            returnStr += "\\u" + Integer.toString(chars[i], 16);
        }
        return returnStr;
    }

}
